<template>
    <div class="quotation-wrapper">
        <!-- 头部区域 -->
        <div class="header">
            <h2>报价单 <span v-if="code">编号:{{ code }}</span></h2> 
            <div class="header-right">  
                <el-button type="primary" @click="saveAndNew" :disabled="isViewOnly">保存并新增</el-button>
                <el-button type="primary" @click="save" :disabled="isViewOnly">保存</el-button>
                <el-button @click="submit" :disabled="isViewOnly">提交</el-button>
                <el-button @click="audit" :disabled="isViewOnly">审核</el-button>
            </div>
        </div>

        <!-- 表单区域 -->
        <el-form :model="quotationForm" :rules="quotationRules" ref="quotationFormRef" label-width="100px"
            class="quotation-form" :disabled="isViewOnly">
            <div class="form-row">
                <el-form-item label="*单据日期：" prop="confirmDate">
                    <el-date-picker v-model="quotationForm.confirmDate" type="date" aria-readonly="fales"
                        style="width: 200px;" />
                </el-form-item>

                <el-form-item label="*报价类型：" prop="customer_type">
                    <el-select v-model="quotationForm.customer_type" clearable style="width: 200px;"
                        @change="quotationTypeChange">
                        <el-option key="1" label="客户" value="1" />
                        <el-option key="2" label="客户类别" value="2" />
                        <el-option key="3" label="客户等级" value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="*报价主体：" prop="customerName">
                    <el-select v-model="quotationForm.customerId" placeholder="请选择" clearable style="width: 200px;"
                        @change="handleCustomerChange">
                        <template v-if="quotationForm.customer_type == 1">
                            <el-option v-for="customer in customerList" :key="customer.code" :label="customer.name"
                                :value="customer.id" />
                        </template>
                        <template v-else-if="quotationForm.customer_type == 2">
                            <el-option v-for="type in customerTypeList" :key="type.id" :label="type.name"
                                :value="type.id" />
                        </template>
                        <template v-else-if="quotationForm.customer_type == 3">
                            <el-option v-for="level in customerLevelList" :key="level.id" :label="level.name"
                                :value="level.id" />
                        </template>
                    </el-select>
                </el-form-item>

                <el-form-item label="销售员：" prop="workName">
                    <el-input v-model="quotationForm.workName" placeholder="业务员" style="width: 200px;" readonly />
                </el-form-item>

                <el-form-item label="*有效日期：" prop="start_date">
                    <el-date-picker v-model="dateRange" type="datetimerange" range-separator="~"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;"
                        @change="handleDateChange" />
                </el-form-item>

                <el-form-item label="客户地址：" prop="customer_address"
                    v-if="quotationForm.customer_type == 1 || quotationForm.customer_type == '客户'">
                    <el-input v-model="quotationForm.customer_address" placeholder="客户地址" style="width: 200px;" />
                </el-form-item>

            </div>
            <div style="height: 50px;"></div>
            <!-- 商品表格 -->
            <el-table :data="orderDetails" border stripe ref="tableRef" show-summary :summary-method="getSummaries"
                summary-row-class-name="summary-row" v-if="orderDetails">
                <!-- 序号列 -->
                <el-table-column label="序号" width="80" align="center">
                    <template #default="scope">
                        <div class="seq-cell" @mouseenter="hoverIndex = scope.$index" @mouseleave="hoverIndex = -1"
                            v-if="!isAudited">
                            <span v-show="hoverIndex !== scope.$index" class="seq-number">
                                {{ scope.$index + 1 }}
                            </span>
                            <div v-show="hoverIndex === scope.$index" class="operation-area">
                                <span class="operation-btn add" @click.stop="addRow(scope.$index)"
                                    title="在下方添加行">+</span>
                                <span class="operation-btn delete" @click.stop="deleteRow(scope.row)" title="删除当前行"
                                    :class="{ disabled: orderDetails.length <= 1 }"
                                    :disabled="orderDetails.length <= 1">−</span>
                            </div>
                        </div>
                        <div v-else class="seq-cell">{{ scope.$index + 1 }}</div>
                    </template>
                </el-table-column>

                <!-- 商品列 -->
                <!-- <el-table-column label="商品" align="center" min-width="150">
                    <template #default="scope">
                        <div class="product-cell" @click="!isAudited && openProductDialog(scope.$index)"
                            :style="{ cursor: isAudited ? 'default' : 'pointer' }">
                            <el-tag v-if="scope.row.productInfo?.name" closable
                                @close="!isAudited && clearProduct(scope.row)" type="info"
                                :disable-transitions="isAudited">
                                {{ scope.row.productInfo.name }}
                            </el-tag>
                            <span v-else class="placeholder-text">请点击选择商品</span>
                        </div>
                    </template>
                </el-table-column> -->

                <!-- 商品 -->
                <el-table-column label="商品" width="180" align="center">
                    <template #default="scope">
                        <template v-if="scope.row.productInfo">
                            <el-input v-model="scope.row.productInfo.name" style="width: 95%" placeholder="选择商品"
                                @click="openGoodsDialog(scope.row, scope.$index)" readonly />
                        </template>

                    </template>
                </el-table-column>


                <el-table-column label="商品编号" align="center" width="100">
                    <template #default="scope">
                        {{ scope.row.goods_code || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="商品图片" align="center" width="100">
                    <template #default="scope">
                        <el-image v-if="scope.row.productInfo?.photo" :src="scope.row.productInfo.photo"
                            style="width: 50px; height: 50px" fit="cover"
                            :preview-src-list="[scope.row.productInfo.photo]" />
                    </template>
                </el-table-column>

                <!-- <el-table-column label="单位" align="center" width="120">
                    <template #default="scope">
                        <el-select v-model="scope.row.selectedUnit" @change="handleUnitChange(scope.row)"
                            :disabled="isAudited || !scope.row.unitList || scope.row.unitList.length <= 1"
                            style="width: 100%;">
                            <el-option v-for="unit in scope.row.unitList" :key="unit.id" :label="unit.name"
                                :value="unit.id" />
                        </el-select>
                    </template>
                </el-table-column> -->

                <!-- 采购单位 -->
                <el-table-column label="单位" width="120" align="center">
                    <template #default="scope">
                        <el-select v-if="scope.row.productInfo" v-model="scope.row.productInfo.unitId"
                            style="width: 95%" :disabled="!scope.row.goodsId" @change="updateUnitName(scope.row)">
                            <template v-if="scope.row.productInfo.unitList">
                                <el-option v-for="item in scope.row.productInfo.unitList" :key="item.id"
                                    :label="item.name" :value="item.id" />
                            </template>
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="基本单位" align="center" width="100">
                    <template #default="scope">
                        {{ scope.row.baseUnit?.name || scope.row.productInfo?.unit || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="订购数量" align="center" width="120">
                    <template #default="scope">
                        <div>
                            <el-input v-model.number="scope.row.quantity" type="number" min="1" step="1"
                                style="width: 100%;" @change="handleQuantityChange(scope.row)"
                                :disabled="isAudited || scope.row.gift" />
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="基本数量" align="center" width="100" prop="baseQuantity">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.baseQuantity" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="规格" align="center" width="80">
                    <template #default="scope">
                        {{ scope.row.productInfo?.specification || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="品牌" align="center" width="80">
                    <template #default="scope">
                        {{ scope.row.productInfo?.brand || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="仓库" width="120" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.warehouse" readonly placeholder="(所有)"
                            @click="openWarehouseDialog(scope.row)" />
                    </template>
                </el-table-column>


                <!-- 赠品列：改为复选框 -->
                <el-table-column label="赠品" align="center" width="120">
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.gift" @change="handleGiftChange(scope.row)"
                            :disabled="isAudited" />
                    </template>
                </el-table-column>

                <el-table-column label="报价单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.price" type="number" min="0" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>

                <el-table-column label="折扣率(%)" align="center" width="100">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discount" type="number" min="0" max="100" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>

                <el-table-column label="折扣额" align="center" width="100" prop="discountAmount">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discountAmount" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="折扣单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discountPrice" type="number" step="0.01"
                            style="width: 100%;" disabled />
                    </template>
                </el-table-column>

                <el-table-column label="金额" align="center" width="100" prop="salesCost">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.salesCost" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="税率(%)" align="center" width="100">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.tax" type="number" min="0" max="100" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>

                <el-table-column label="税额" align="center" width="100" prop="taxAmount">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.taxAmount" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="税后单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.taxPrice" type="number" step="0.01" style="width: 100%;"
                            disabled />
                    </template>
                </el-table-column>



                <el-table-column label="价税合计" align="center" width="120" prop="totalPrice">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.totalPrice" type="number" step="0.01" style="width: 100%;"
                            disabled />
                    </template>
                </el-table-column>

                <el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.remarks" placeholder="请输入备注" :disabled="isAudited"
                            style="width: 100%;" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 50px;"></div>
            <!-- 下方表单 -->
            <div class="form-row" style="padding-top: 20px;">
                <el-form-item label="交货方式：" prop="delivery">
                    <el-select v-model="quotationForm.delivery" placeholder="请选择" style="width: 200px;" clearable>
                        <el-option value="1" label="快递物流" />
                        <el-option value="2" label="自配" />
                        <el-option value="3" label="其他" />
                    </el-select>
                </el-form-item>

                <el-form-item label="收款条件：" prop="payment">
                    <el-select v-model="quotationForm.payment" placeholder="请选择" style="width: 200px;" clearable>
                        <el-option value="1" label="现结" />
                        <el-option value="2" label="货到付款" />
                        <el-option value="3" label="分期付款" />
                        <el-option value="4" label="先款后付" />
                        <el-option value="5" label="月结" />
                        <el-option value="6" label="不定期付款" />
                    </el-select>
                </el-form-item>
            </div>

            <div class="form-row full-width-row">
                <el-form-item label="备注：" prop="remarks" class="full-width-item">
                    <el-input v-model="quotationForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息"
                        style="width: 900px;" />
                </el-form-item>
            </div>
        </el-form>

        <!-- 商品选择弹窗 -->
        <!-- <el-dialog v-model="productDialogVisible" title="选择商品" width="50%" draggable :show-close="true"
            @close="handleProductCancel">
            <FreeGoodsSelect ref="FreeGoodsRef" v-model="productDialogVisible" @confirm="handleProductConfirm" />
        </el-dialog> -->

        <!-- 商品搜索列表弹出对话框 -->
        <FreeGoodsSelect ref="FreeGoodsRef" v-model="showSelectGoods" @confirm="handleSelectedGoods" />



        <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
            :show-close="true">
            <!-- 调用仓库的搜索组件 -->
            <WareHouse ref="warehouseRef"
                :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
            <br /><br />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="warehouseVisible = false">取消</el-button>
                    <el-button type="primary" @click="warehouseVisible = false">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import FreeGoodsSelect from '@/util/FreeGoodsSelect.vue'
import axios from 'axios'
import WareHouse from '@/views/basic/WareHouse.vue'

let FreeGoodsRef = ref();
const updateUnitName = (row) => {
  const { productInfo } = row;
  if (!productInfo?.unitList || !productInfo.unitId) {
    productInfo.unitName = null;
    return;
  }
  const selectedUnit = productInfo.unitList.find(u => u.id === productInfo.unitId);
  productInfo.unitName = selectedUnit ? selectedUnit.name : null;
  console.log("当前的unitName:", productInfo.unitName);
  handleUnitChange(row)
};
// 商品搜索对话框展示
const showSelectGoods = ref(false)
function openGoodsDialog(row, index) {
  showSelectGoods.value = true
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}

const route = useRoute()

const staffName = sessionStorage.getItem("name") || '';

const isEditable = computed(() => {
    // 如果是从编辑页面进入，且状态为待审核(1)或已审核(2)，则不可编辑
    if (route.query.from === 'edit' && (route.query.status === '1' || route.query.status === '2')) {
        return false
    }
    return true
})
// 计算属性：是否为查看模式
const isViewOnly = computed(() => !isEditable.value)

// 计算属性：是否为编辑模式
const isEdit = computed(() => route.query.from === 'edit')
const quotationId = computed(() => route.query.id)
// 当前是否已审核
const isAudited = ref(false)

// 报价单主表
const quotationForm = reactive({
    id: '',
    confirmDate: Date.now(),
    customerId: '',
    customer_type: '',
    customerName: '',
    workName: staffName,
    workNumber: '',
    customer_address: '',
    start_date: new Date(),
    end_date: '',
    payment: '',
    delivery: '',
    remarks: '',
})

const quotationTypeChange = () => {
    // 当报价类型发生变化时，清空报价主体
    quotationForm.customerName = ''
    quotationForm.customerId = ''
    quotationForm.customer_address = ''
}
watch(() => quotationForm.customerName, (newVal) => {
    if (quotationForm.customer_type === '1' && newVal) {
        // 查找选中的客户
        const selectedCustomer = customerList.value.find(customer => customer.name === newVal)
        if (selectedCustomer) {
            // 如果客户数据中包含地址信息，则自动填充
            if (selectedCustomer.primaryContactAddress) {
                quotationForm.customer_address = selectedCustomer.primaryContactAddress
            }
        }
    }
})
const code = ref('')

const dateRange = ref([])


// 商品弹窗控制
const productDialogVisible = ref(false)

// 鼠标悬停行索引
const hoverIndex = ref(-1)
const tableRef = ref(null)

const customerList = ref([
])
const customerTypeList = ref([
])
const customerLevelList = ref([
])

let currentRow = ref(null), currentIndex = ref(null);
//仓库搜索选中结果
let warehouseVisible = ref(false)
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
            currentRow.value.warehouse = warehouseRef.value.selectedArray[0].name //只选择一个，默认第一个
            //   currentRow.value.warehouseCode = warehouseRef.value.selectedArray[0].code //只选择一个，默认第一个
            //获取到仓库编码，存数据库用，仓库name仅用作展示
            //用完之后清空，避免污染其他地方数据
            warehouseRef.value.clearSelected();
        }
    }
})
function openWarehouseDialog(row) {
    warehouseVisible.value = true,
        currentRow.value = row;
}
// 打开商品选择弹窗
// const openProductDialog = (index) => {
//     currentIndex.value = index
//     productDialogVisible.value = true
// }

// 清除商品
// const clearProduct = (row) => {
//     row.productInfo = null
//     row.price = 0
//     row.goods_code = null
//     row.warehouse = null
//     calculateDetailPrice(row)
// }

// 添加行
const addRow = (index) => {
    const newRow = emptyRow()
    orderDetails.value.splice(index + 1, 0, newRow)
}

// 删除行
const deleteRow = (row) => {
    if (orderDetails.value.length <= 1) {
        return ElMessage.warning('至少保留一条商品明细')
    }
    orderDetails.value = orderDetails.value.filter(r => r.id !== row.id)
}

// 格式化价格：保留两位小数
const formatPrice = (num) => Math.round(num * 100) / 100

// 处理赠品勾选
const handleGiftChange = (row) => {
    if (row.gift) {
        // 保存原始价格
        row._originalPrice = {
            price: row.price,
            discount: row.discount,
            tax: row.tax,
            quantity: row.quantity || 0
        }
        // 清零
        row.price = 0
        row.discount = 0
        row.tax = 0
        row.discountAmount = 0
        row.discountPrice = 0
        row.taxAmount = 0
        row.taxPrice = 0
        row.salesCost = 0
        row.totalPrice = 0
    } else {
        const original = row._originalPrice
        row.price = original?.price ?? row.productInfo?.defaultPrice ?? 0
        row.discount = original?.discount ?? 0
        row.tax = original?.tax ?? 13
        row.quantity = original?.quantity
        calculateDetailPrice(row)
    }
}

// 价格计算
const calculateDetailPrice = (row) => {
    if (row.gift) {
        row.discountAmount = 0
        row.discountPrice = 0
        row.taxPrice = 0
        row.salesCost = 0
        row.totalPrice = 0
        row.taxAmount = 0
    } else {
        if (!row.productInfo || !row.price || !row.quantity || row.quantity < 1) {
            row.discountPrice = 0
            row.taxPrice = 0
            row.totalPrice = 0
            row.salesCost = 0
            row.taxAmount = 0
            row.discountAmount = 0
        } else {
            row.discountPrice = formatPrice(row.price * (1 - (row.discount || 0) / 100))
            row.taxPrice = formatPrice(row.discountPrice * (1 + (row.tax || 0) / 100))
            // 使用基本数量计算成本和总价
            row.salesCost = formatPrice(row.discountPrice * (row.baseQuantity || row.quantity))
            row.totalPrice = formatPrice(row.taxPrice * (row.baseQuantity || row.quantity))
            row.taxAmount = formatPrice((row.taxPrice - row.discountPrice) * (row.baseQuantity || row.quantity))
            row.discountAmount = formatPrice((row.price - row.discountPrice) * (row.baseQuantity || row.quantity))
        }
    }
}


// 合计行
const getSummaries = ({ columns, data }) => {
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        if (column.property === 'baseQuantity') {
            sums[index] = data.reduce((sum, row) => sum + (row.baseQuantity || 0), 0)
            return
        }
        
        if (column.property === 'totalPrice') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.totalPrice || 0), 0))
            return
        }

        if (column.property === 'salesCost') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.salesCost || 0), 0))
            return
        }
        if (column.property === 'taxAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.taxAmount || 0), 0))
            return
        }
        if (column.property === 'discountAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.discountAmount || 0), 0))
            return
        }
        sums[index] = ''
    })
    return sums
}


// 商品选择确认
const handleSelectedGoods = (selected) => {
    if (!selected || selected.length === 0) return
    console.log("选择的商品信息:", selected);

    const newRows = selected.map(item => {
        // 获取默认单位
        let unitList = item.unitList || [];
        let baseUnit = null;
        let unitConversion = 1;


        const row = {
            id: Date.now() + Math.random(),
            productInfo: {
                goodsId: item.id,
                name: item.name,
                goods_code: item.code,
                photo: item.photo || '',
                unitId: item.unit,
                unit: item.unitName,
                unitList: unitList,
                specification: item.specification,
                brand: item.brandName,
                defaultPrice: item.price || item.defaultPrice || 0,
                warehouseName: item.warehouseName,
            },
            goodsId: item.id,
            goods_code: item.code,
            warehouse: item.warehouseName,
            gift: false,
            price: item.defaultPrice || 0,
            discount: 0,
            tax: 13,
            quantity: 0,
            discountPrice: 0,
            taxAmount: 0,
            discountAmount: 0,
            salesCost: 0,
            taxPrice: 0,
            totalPrice: 0,
            remarks: '',
            // 多单位相关字段
            unitList: unitList,
            // selectedUnit: selectedUnit?.id || null,
            baseUnit: baseUnit,
            unitConversion: unitConversion,
            baseQuantity: 0
        };

        
        // 计算价格
        if (!row.gift) {
            calculateDetailPrice(row);
        }

        return row;
    });

    console.log("newRows:", newRows);

    // 如果当前是编辑某一行（比如点击某行商品触发）,则替换该行,否则追加到末尾
    if (currentIndex.value !== null && orderDetails.value[currentIndex.value]) {
        orderDetails.value.splice(currentIndex.value, 1, ...newRows)
    } else {
        orderDetails.value.push(...newRows)
    }

    productDialogVisible.value = false
}
// 单位变更处理
const handleUnitChange = (row) => {
    if (!row.productInfo?.unitName || !row.productInfo.unitList) return;

    // 查找选中的单位
    const selectedUnit = row.productInfo.unitList.find(u => u.id == row.productInfo.unitId);
    if (selectedUnit) {
        row.sunitConversion = selectedUnit.conversion || 1;
        row.baseQuantity = Math.round((row.quantity || 0) * row.sunitConversion * 100) / 100;
        console.log(row.baseQuantity)
        calculateDetailPrice(row);
    }
}
// 切换单位，保持 baseQuantity 不变，更新 quantity 显示
// const handleUnitChange = (row) => {
//     if (!row?.productInfo?.unitName || !Array.isArray(row.unitList) || !row.selectedUnit) {
//         return;
//     }

//     const selectedUnit = row.unitList.find(u => u.id === row.selectedUnit);
//     const conversion = selectedUnit?.conversion ?? 1;

//     row.unitConversion = conversion;
//     // 从 baseQuantity 反推当前单位的数量
//     row.quantity = conversion ? Math.round((row.baseQuantity || 0) / conversion * 100) / 100 : 0;

//     calculateDetailPrice(row);
// };


// 数量变更处理
const handleQuantityChange = (row) => {
  if (!row.productInfo?.unitId || !row.productInfo.unitList) return;

  // 查找选中的单位
  const selectedUnit = row.productInfo.unitList.find(u => u.id == row.productInfo.unitId);
  if (selectedUnit) {
    row.sunitConversion = selectedUnit.conversion || 1;
    row.baseQuantity = Math.round((row.quantity || 0) * row.sunitConversion * 100) / 100;
    console.log("基础数量更新为:", row.baseQuantity);
    calculateDetailPrice(row);
  }
}
// 商品弹窗取消
// const handleProductCancel = () => {
//     productDialogVisible.value = false
//     currentIndex.value = null
// }

// 日期范围变化的方法
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        quotationForm.start_date = val[0]
        quotationForm.end_date = val[1]
    } else {
        quotationForm.start_date = null
        quotationForm.end_date = null
    }
}
// 日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

//客户主体
const handleCustomerChange = (customerId) => {
    // 清空地址和名称
    quotationForm.customerName = ''
    quotationForm.customer_address = ''

    if (!customerId) return

    let selected

    if (quotationForm.customer_type == 1) {
        selected = customerList.value.find(c => c.id === customerId)
        if (selected) {
            quotationForm.customerName = selected.name
            if (selected.primaryContactAddress) {
                quotationForm.customer_address = selected.primaryContactAddress
            }
        }
    } else if (quotationForm.customer_type == 2) {
        selected = customerTypeList.value.find(t => t.id === customerId)
        if (selected) {
            quotationForm.customerName = selected.name
        }
    } else if (quotationForm.customer_type == 3) {
        selected = customerLevelList.value.find(l => l.id === customerId)
        if (selected) {
            quotationForm.customerName = selected.name
        }
    }
}

// 修改,保存
const save = async () => {


    const validDetails = orderDetails.value.filter(detail => detail.productInfo);

    if (validDetails.length === 0) {
        ElMessage.error('请至少选择一个商品进行保存')
        return false
    }


    for (let detail of validDetails) {
        if (!detail.quantity || detail.quantity <= 0 || !Number.isInteger(detail.quantity)) {
            ElMessage.error('订购数量必须为正整数')
            return false
        }
    }


    if (!quotationForm.confirmDate) {
        ElMessage.error('请选择单据日期')
        return false
    }

    if (!quotationForm.customer_type) {
        ElMessage.error('请选择报价类型')
        return false
    }

    if (!quotationForm.start_date) {
        ElMessage.error('请选择有效开始日期')
        return false
    }

    if (!quotationForm.end_date) {
        ElMessage.error('请选择有效结束日期')
        return false
    }


    try {
        await ElMessageBox.confirm('确定要保存此报价吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
    } catch {
        return false
    }


    const quotation = {
        code: code.value,
        confirmDate: formatDate(quotationForm.confirmDate),
        customer_type: customerTypeValueMap[quotationForm.customer_type] || quotationForm.customer_type,
        customerName: quotationForm.customerName,
        customerId: quotationForm.customerId,
        workName: quotationForm.workName,
        customer_address: quotationForm.customer_address,
        start_date: formatDate(quotationForm.start_date),
        end_date: formatDate(quotationForm.end_date),
        payment: paymentValueMap[quotationForm.payment] || quotationForm.payment,
        delivery: deliveryValueMap[quotationForm.delivery] || quotationForm.delivery,
        remarks: quotationForm.remarks,
        orderPrice: orderDetails.value.reduce((sum, row) => sum + (row.totalPrice || 0), 0),
        itemCount: orderDetails.value.reduce((sum, row) => sum + (row.baseQuantity || 0), 0),
    }

    // 选中的商品
    const quotationDetList = validDetails.map((detail) => {
        const p = detail.productInfo || {}
        // 查找选中的单位对象以获取 unitsId 和 name
        console.log("goods-----------:",detail);
        return {
            goodsId: detail.goodsId,
            goods_code: p.code || detail.goods_code || '',
            name: p.name || '',
            warehouse: detail.warehouse,
            price: formatPrice(detail.price),
            discount: formatPrice(detail.discount),
            tax: formatPrice(detail.tax),
            quantity: detail.quantity,
            baseQuantity: detail.baseQuantity,
            gift: detail.gift ? 1 : 0,
            discountPrice: formatPrice(detail.discountPrice),
            taxPrice: formatPrice(detail.taxPrice),
            salesCost: formatPrice(detail.salesCost),
            totalPrice: formatPrice(detail.totalPrice),
            remarks: detail.remarks,
            discountAmount: formatPrice(detail.discountAmount),
            taxAmount: formatPrice(detail.taxAmount),
            unit: p.unit || '',
            specification: p.specification || '',
            brand: p.brand || '',
            moreUnit: p.unitName|| p.name  ,

        }
    })

    if (code.value) {
        // 编辑模式
        const response = await axios.post('/api/sales/updateQuotation', {
            quotation: {
                ...quotation,
                id: quotationId.value || quotationForm.id,
            },
            quotationDetList: quotationDetList
        })
        if (response.data.code == 200) {
            ElMessage.success('修改成功')
            return true
        } else {
            ElMessage.error('修改失败 : ' + response.data.msg)
            return false
        }
    } else {
        // 新增模式
        const response = await axios.post('/api/sales/quotationAdd', {
            quotation: quotation,
            quotationDetList: quotationDetList
        })
        if (response.data.code == 200) {
            code.value = response.data.quotationCode
            quotationForm.id = response.data.id
            ElMessage.success('保存成功')
            return true
        } else {
            ElMessage.error('保存失败 : ' + response.data.msg)
            return false
        }
    }

}
// 修改保存,新增
const saveAndNew = async () => {

    const saveResult = await save()

    if (!saveResult) {
        return
    }

    // 保存成功，执行重置操作
    Object.assign(quotationForm, {
        confirmDate: Date.now(),
        customer_type: '',
        customerName: '',
        workName: staffName,
        customer_address: '',
        start_date: '',
        end_date: '',
        payment: '',
        delivery: '',
        remarks: ''
    })

    orderDetails.value = [emptyRow()]
    dateRange.value = []
    code.value = ''
    isAudited.value = false
    productDialogVisible.value = false
    currentIndex.value = 0
    hoverIndex.value = -1

}
const submit = async() => { 
    // const response = await axios.get('/api/sales/submitQuotation', {
    //     params: { id: quotationForm.id }
    // })
    isAudited.value = true
    ElMessage.success('已提交')
}
// 审核
const audit = async() => {
    isAudited.value = true
    ElMessage.success('已审核')
}

// 空行
const emptyRow = () => ({
    id: Date.now(),
    goodsId: '',
    productInfo: {

    },
    goods_code: '',
    warehouse: '',
    gift: false,
    price: 0,
    discount: 0,
    tax: 13,
    quantity: 0,
    discountPrice: 0,
    salesCost: 0,
    discountAmount: 0,
    taxAmount: 0,
    taxPrice: 0,
    totalPrice: 0,
    remarks: '',

    unitList: [],
    selectedUnit: null,
    baseUnit: null,
    baseQuantity: 0,
    unitConversion: 1
})



// 明细表数据
const orderDetails = ref([
    emptyRow()
])

// 修改回显
const fetchQuotationDetail = async (codeParam ) => {

    const from = route.query.from
    if (from === 'edit') {
        isEdit.value = true
        isViewOnly.value = false
    } else if (from === 'view') {
        isViewOnly.value = true
        isEdit.value = false
    }


    const response = await axios.get('/api/sales/quotationByCode', {
        params: { code: codeParam  }

    })
    if (response.data.code == 200) {
        const quotation = response.data.quotation
        console.log('quotation:', quotation)
        const quotationDetList = response.data.quotationDetList || []

        // 回显主表数据
        code.value = quotation.code || ''
        quotationForm.confirmDate = quotation.confirmDate ? new Date(quotation.confirmDate) : new Date()
        quotationForm.customer_type = customerTypeLabelMap[quotation.customer_type] || quotation.customer_type

        quotationForm.customerId = quotation.customerId || ''
        const customerTypeValue = String(quotation.customer_type)

        quotationForm.customer_type = customerTypeValue;

        let customerTypeName = ''

        if (customerTypeValue === '1') {
            const found = customerList.value.find(c => c.id === quotation.customerId)
            customerTypeName = found ? found.name : ''
        } else if (customerTypeValue === '2') {
            const found = customerTypeList.value.find(t => t.id === quotation.customerId)
            customerTypeName = found ? found.name : ''
        } else if (customerTypeValue === '3') {
            const found = customerLevelList.value.find(l => l.id === quotation.customerId)
            customerTypeName = found ? found.name : ''
        }

        quotationForm.customerName = customerTypeName
        quotationForm.workName = quotation.workName || ''
        quotationForm.customer_address = quotation.customer_address || ''
        quotationForm.start_date = quotation.start_date ? new Date(quotation.start_date) : new Date()
        quotationForm.end_date = quotation.end_date ? new Date(quotation.end_date) : ''
        quotationForm.payment = paymentLabelMap[quotation.payment] || quotation.payment
        quotationForm.delivery = deliveryLabelMap[quotation.delivery] || quotation.delivery
        quotationForm.remarks = quotation.remarks || ''
        quotationForm.id = quotation.id || ''

        // 设置日期范围
        if (quotation.start_date && quotation.end_date) {
            dateRange.value = [new Date(quotation.start_date), new Date(quotation.end_date)]
        }

        console.log('quotationDetList', quotationDetList)
        // 回显明细表数据
        orderDetails.value = quotationDetList.map((item) => ({
            id: item.goodsId,
            goodsId: item.goodsId || '',
            goods_code: item.goods_code || '',
            productInfo: item.goodsId ? {
                name: item.name,
                moreUnit: item.moreUnit || '',
                utilId: null,
                unit: item.unit || '',
                specification: item.specification || '',
                brand: item.brand || '',
            } : null,
            warehouse: item.warehouse || '',
            price: item.price || 0,
            discount: item.discount || 0,
            tax: item.tax || 13,
            quantity: item.quantity || 0,
            gift: item.gift == 1 ? true : false,
            discountPrice: item.discountPrice || 0,
            taxPrice: item.taxPrice || 0,
            salesCost: item.salesCost || 0,
            totalPrice: item.totalPrice || 0,
            remarks: item.remarks || '',
            taxAmount: item.taxAmount || 0,
            baseQuantity: item.baseQuantity || 0,
            discountAmount: item.discountAmount || 0
        }))
        console.log(1)
        assignUnitList();
        console.log(2)


    } else {
        ElMessage.error('获取报价单详情失败: ' + response.data.msg)
    }
}

//--------------------------------
const assignUnitList = () => {
    const map = FreeGoodsRef.value?.unitOptionsMap;
    if (!map) {
        setTimeout(assignUnitList, 100);
        return;
    }
    console.log(3)
    // 检查是否所有商品的 unitList 都已加载
    const allLoaded = orderDetails.value.every(i => {
        const goodsId = String(i.goodsId).trim();
        return map[goodsId] !== undefined;
    });
    console.log(4)
    if (!allLoaded) {
        setTimeout(assignUnitList, 100);
        return;
    }
    console.log(5)
    // ✅ 开始赋值 unitList 和 unitId
    console.log("map")
    console.log(map)
    orderDetails.value.forEach(i => {
        const goodsId = String(i.goodsId).trim();
        const unitList = map[goodsId] || [];
        console.log("unitList:", unitList);
        i.productInfo.unitList = unitList;

        // 如果已经有 unitId（比如后端返回了），就保留        -------------------------从此处后面的视情况赋值，这里unitId为null是从其他单生成入库单时，没有unitId导致的，如果自己的明细中包含unitId，就不用考虑下面的代码
        if (i.productInfo.unitId) {
            return;
        }

        unitList.forEach(j => {
            if (i.productInfo.moreUnit == j.name) {
                i.productInfo.unitId = j.id;
            }
        })


    })
}

const selectOther = async () => {

    const response = await axios.get("/api/sales/selectOtherList")
    console.log("selectOther", response.data)
    if (response.data.code == 200) {
        customerLevelList.value = response.data.customerLevelList || []
        customerTypeList.value = response.data.customerTypeList || []
        customerList.value = response.data.customerList || []
    } else {
        ElMessage.error('获取客户信息失败: ' + response.data.msg)
    }

}

const customerTypeValueMap = {
    '客户': '1',
    '客户类别': '2',
    '客户等级': '3'
}
const customerTypeLabelMap = {
    '1': '客户',
    '2': '客户类别',
    '3': '客户等级'
}
const deliveryValueMap = {
    '快递物流': '1',
    '自配': '2',
    '其他': '3'
}

const paymentValueMap = {
    '现结': '1',
    '货到付款': '2',
    '分期付款': '3',
    '先款后付': '4',
    '月结': '5',
    '不定期付款': '6'
}
const deliveryLabelMap = {
    '1': '快递物流',
    '2': '自配',
    '3': '其他'
}

const paymentLabelMap = {
    '1': '现结',
    '2': '货到付款',
    '3': '分期付款',
    '4': '先款后付',
    '5': '月结',
    '6': '不定期付款'
}

// 初始化
onMounted(async () => {
    await selectOther()
    const codeParam  = route.query.code
    if (codeParam ) {
        await fetchQuotationDetail(codeParam )
    }
})
</script>

<style scoped>
.quotation-wrapper {
    background: white;
    padding: 20px;
    min-height: 85vh;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
}

.header h2 {
    font-size: 1.5rem;
    color: #333;
    margin: 0;
}

.header-right {
    display: flex;
    gap: 8px;
}

.quotation-form {
    background: white;
    padding: 20px;
    border-radius: 4px;

}

.form-row {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    margin-bottom: 15px;
}



.el-form-item__label {
    font-weight: normal;
    color: #333;
    font-size: 14px;
}

.el-table th,
.el-table td {
    padding: 12px 10px;
    text-align: left;
    font-size: 14px;
    border-bottom: 1px solid #e4e7ed;
}

.placeholder-text {
    color: #999;
    font-size: 13px;
}

.summary-row {
    font-weight: bold;
    color: #333;
    background-color: #fffbe6 !important;
}

.operation-area {
    display: flex;
    gap: 4px;
}

.operation-btn {
    cursor: pointer;
    font-weight: bold;
    width: 18px;
    text-align: center;
}

.operation-btn.add:hover {
    color: green;
}

.operation-btn.delete:hover:not(.disabled) {
    color: red;
}

/* 复选框居中 */
.el-table .cell .el-checkbox {
    display: flex;
    justify-content: center;
}

.quotation-form .el-form-item.is-required .el-form-item__label::before {
    content: '*';
    color: red;
    margin-right: 4px;
}
</style>